//
//  QCTool.swift
//  爱汽车
//
//  Created by tucici on 2023/12/23.
//

import UIKit
import TCCKit
class QCTool: NSObject {
    ///返回日期时间的16进制
    class func dateHex(_ stamp:Int)->(date:String,week:String){
        let date = NSDate.dateOfStamp(stamp)
        let week = date.weekday! >= 2 ? date.weekday! - 1 : 7
        let yearStr = "\(date.year!)".toHex().fix(4, "0") as String
        let monthStr = "\(date.month!)".toHex().fix(2, "0") as String
        let dayStr = "\(date.day!)".toHex().fix(2, "0") as String
        let hourStr = "\(date.hour!)".toHex().fix(2, "0") as String
        let minStr = "\(date.minute!)".toHex().fix(2, "0") as String
        let secStr = "\(date.second!)".toHex().fix(2, "0") as String
        let weekStr = "\(week)".toHex().fix(2, "0") as String
        return(date:yearStr+monthStr+dayStr+hourStr+minStr+secStr,week:weekStr)
    }
    ///判断是否连接
    class func noConnect()->Bool{
        if  ["QCHomeViewController"].contains(self.currentVC().className){return true}
        if BLE.connectedPeripherals.count > 0, let per = BLE.connectedPeripherals.first, let services = per.services, services.contains(where: {$0.uuid.uuidString == Nordic_OTA_service}){return true}
        
        if BLE.connectedPeripherals.count<=0{
            let vc = QCAlertPopViewController(useXib: true)
            vc.show("未连接设备","去官网","去连接")
            vc.leftBtnBlock = {
                (APP.window?.rootViewController as! QCTabBarViewController).selectedIndex = 0
            }
            vc.rightBtnBlock = {
                if self.currentVC().className  == "QCSearchController" {
                    return
                }
                let searchVC = QCSearchController()
                self.currentVC().push(searchVC, true)
            }
            return true
        }
        return false
    }
    ///大端字符串，转 小端字符串
    class func reverse(_ str:String)->String{
        var resutl = ""
        var temp = ""
        var i = 0
        for s in str.reversed(){
            if i % 2 == 0 {
                temp  = String(s)
            }else{
                temp = String(s)+temp
                resutl += temp
            }
            i += 1
        }
        return resutl
    }
    
    class func requestAboard(_ block:(()->Void)? = nil){
        ///countryType=0 国内
        ///countryType=1国外
        ///countryType=2 通用
        NetworkTool.request(.gegBroad(APP.contry.rawValue)) { response in
            guard var array = response["data"].arrayObject as? [String] else{ return}
            for name in localProductName{
                if !array.contains(name) {
                    array.append(name)
                }
            }
            let str = array.compactMap{
                let s = "\($0)"
                let result = $0.hasPrefix("0x") ? String(s.suffix(4)) : s
                return result.uppercased()
            }.joined(separator: ",")            
            UserDefaults.standard.setValue(str, forKey: ProductKey)
            UserDefaults.standard.synchronize()
            block?()
        }
    }
    
    class func crc(cmd:UInt8, hex:String,  from:String="04", to:String="01" )->(data:String,crc:String){
        ///1.累加
        func add(_ cmd:UInt8, _ hex:String, _ from:String, _ to:String)->String{
            let cmd_str = String(format: "%.2X", cmd)
            var new_data = from+to+cmd_str+hex
            let l_str = new_data.count/2+1///校验码有1字节
            let length = "\(l_str)".toHex().fix(4, "0") as String
            new_data = length+new_data
            return new_data
        }
        ///2.求和
        func sum(_ data:String)->Int{
            var sum = 0
            for i in 0..<data.count/2{
                let hex = data[i*2...i*2+1]
                sum += hex.toDecimal()
            }
            return sum
        }
        ///3.校验
        func crc(_ sum:Int)->String{
            let str = ((sum ^ 0xff)+1) & 0xFF///结果取反+1，再取低位
            let crc = "\(str)".toHex().fix(2, "0") as String
            return crc
        }
        
        //校验。计算方法：从“长度”到“数据”结束的全部内容累加，所得结果取反+1，再取低位
        let data = add(cmd, hex,from,to)
        let sum  = sum(data)
        let crc = crc(sum)
        return (data,crc)
    }
    
    
}
